import * as Api from '../service';
import utils from '../utils'
/**
 *
 * mobileMixin
 * 手机格式的校验
 */

export const mobileMixin = {
  data() {
    return {
      codeDisabled: true,
      mobileError: {
        showError: false,
        errorMessage: ""
      }
    }
  },
  methods: {
    /**
     *
     * @param {*} value
     * @param {*} cb  判断时间号码是否已注册的回调
     */
    async handleMobileChange(value) {
      if (/^1[1345789]\d{9}$/.test(value)) {
        if (this.ms === 60) {
          this.codeDisabled = false;
        }
      } else {
        this.codeDisabled = true;
      }
      this.setMobileError();
      if (value.toString().length === 11 && !/^1[1345789]\d{9}$/.test(this.model.mobile)) {
        this.setMobileError('该号码格式错误', true);
      }
      if (value.toString().length === 11 && /^1[1345789]\d{9}$/.test(this.model.mobile)) {
        try {
          await Api.checkMobild({ mobile: value })
        } catch (error) {
          if (error.code === "10002") {
            this.setMobileError('手机号码已注册', true);
          }
        }
      }
    },
    handleMobileBlur() {
      console.log('---===')
      console.log(this.model.mobile)
      console.log(this.model.mobile.toString().length)
      if (this.model.mobile.toString().length > 0 && !/^1[1345789]\d{9}$/.test(this.model.mobile)) {
        console.log('---')
        this.setMobileError('手机号码有误，请重新输入', true);
      } else if (!this.mobileError.showError) {
        this.setMobileError();
      }
    },
    setMobileError(message = '', flag = false) {
      this.mobileError = {
        errorMessage: message,
        showError: flag
      }
    }
  }
}

/**
 *
 * spaceMixin
 * 空格校验
 */
export const toolsMixin = {
  methods: {
    checkEmpty(val) {
      if (val.indexOf(' ') === -1)
        return true
      else
        return false
    }
  }
}

/**
 *
 * nameMixin
 * 名称校验
 */
export const nameMixin = {
  data() {
    return {
      nameError: {
        showError: false,
        errorMessage: ""
      }
    }
  },
  methods: {
    handleNameBlur() {
      if (this.model.name) {
        this.setNameError();
      }
    },
    setNameError(message = '', flag = false) {
      this.nameError = {
        errorMessage: message,
        showError: flag
      }
    }
  }
}

/**
 *
 * addressMixin
 * 地址校验
 */
export const addressMixin = {
  data() {
    return {
      addressError: {
        showError: false,
        errorMessage: ""
      }
    }
  },
  methods: {
    setAddressError(message = '', flag = false) {
      this.addressError = {
        errorMessage: message,
        showError: flag
      }
    }
  }
}
export const codeMixin = {
  data() {
    return {
      codeError: {
        showError: false,
        errorMessage: ""
      },
      text: "获取验证码",
      codeRetry: false,
      ms: 60
    }
  },
  methods: {
    setCodeError(message = '', flag = false) {
      this.codeError = {
        errorMessage: message,
        showError: flag
      }
    },
    handleCodeBlur() {
    },
    async getCode(mobile) {
      try {
        this.codeDisabled = true;
        const data = await Api.sendCode({ mobile: mobile });
        this.timer();
      } catch (e) {
        this.codeDisabled = false;
        if (e.code == "10002") {
          this.setMobileError('手机号码已注册', true);
        } else {
          alert(e.message);
        }
      }
    },
    timer() {
      const timer = setInterval(() => {
        this.ms -= 1;
        this.text = `重新获取(${this.ms})`;
        this.codeRetry = true;
        if (this.ms === 0) {
          this.codeRetry = false
          this.codeDisabled = false;
          this.text = "获取验证码";
          this.ms = 60;
          clearInterval(timer);
        }
      }, 1000);
    }
  }
}
export const mixin = {
  methods: {
    submit(e) {
      e.preventDefault()
      this.$refs.form.validate(async valid => {
        console.log(valid)
        if (!valid)
          return false;
        let errorRecord = false;
        if (this.mobileError.showError)
          errorRecord = true;

        if (!this.checkEmpty(this.model.name)) {
          this.setNameError('姓名不允许带空格', true);
          errorRecord = true;
        }

        if (this.model.orderType === '1' && !this.checkEmpty(this.model.address)) {
          this.setAddressError('地址不允许带空格', true);
          errorRecord = true;
        }

        if (errorRecord)
          return;
        if (this.loading) return

        this.loading = true;
        try {
          const params = this.formatData();
          const { data } = await Api.userRegister(params)
          localStorage.setItem('camellia-sample-discern', data.discern)
          localStorage.removeItem('camellia-sample-crmInfo')
          this.$router.push({ path: '/result', query: { discern: data.discern } })
        } catch (error) {
          this.checkResponse(error);
        } finally {
          this.loading = false;
        }
      });
    },
    async getCrmUser() {
      if (!utils.queryString().code)
        return;
      try {
        let { data } = await Api.getCrmUser({ code: utils.queryString().code });
        this.model.type = 1;
        this.model.name = data.name;
        this.model.mobile = data.mobile;
        this.model.openId = data.openId;
        this.codeDisabled = false;
        localStorage.setItem('camellia-sample-crmInfo', JSON.stringify(data))
      } catch (error) {
        const data = JSON.parse(localStorage.getItem('camellia-sample-crmInfo'))
        if (data) {
          this.model.type = 1;
          this.model.name = data.name;
          this.model.mobile = data.mobile;
          this.codeDisabled = false;
        } else {
          // alert(error.message)
        }
      }
    },
    checkResponse(e) {

      if (e.code === '10011') {
        alert("参数错误");
      } else if (e.code === "10006") {
        this.$router.replace('/result')
        localStorage.setItem('camellia-sample-discern', data.discern)
        localStorage.removeItem('camellia-sample-crmInfo')
      } else if (e.code === "10002") {
        alert("手机号码已注册");
        this.$router.replace('/result')
        localStorage.setItem('camellia-sample-discern', data.discern)
        localStorage.removeItem('camellia-sample-crmInfo')
      } else if (e.code === "10012") {
        // alert("验证码超时");
        this.setCodeError('验证码超时', true);
      } else if (e.code === "10013") {
        // alert("验证码错误");
        this.setCodeError('验证码错误', true);
      } else if (e.code === "10004") {
        alert("未找到数据");
      } else if (e.code === "10003") {
        // alert('预约已满')
        this.$router.push({ path: '/over' })
        console.log(e.code === "10003")
        localStorage.removeItem('camellia-sample-discern', data.discern)
      } else {
        alert(e.message);
      }
    }
  }

}
